/**
 * 				MochitoServerRuntime.java
 *				------------
 *		
 *   Author:	bin04017@gmail.com
 *	 Created:	22.12.2006
 *	 Project:	Mochito-TransferFramework
 *	 Package:	mochitoConnection.interfaces.server.rmi
 *	 Usage:		starts mochito server thread
 * *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */
package mochitoConnection.rmi.server;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import mochitoTransferFactory.MochitoException;
import mochitoTransferFactory.mochitoHost.MochitoHost;

public class MochitoServerRuntime implements Runnable {

	private MochitoServerRMI server = null;

	public MochitoServerRuntime(String host) throws MochitoException,
			RemoteException {
		init(host);
	}

	public MochitoServerRuntime(MochitoHost host) throws MochitoException,
			RemoteException {
		init(host.getHostAsString());
	}

	private void init(String host) throws RemoteException, MochitoException {
		server = new MochitoServerRMI(host);
	}

	public void run() {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
		}
		try {
			LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
		}

		catch (RemoteException ex) {
			System.out.print(ex);
		}
		try {
			System.out.println("Starting Server: rmi://"
					+ server.getHostAsString() + "/Mochito");
			Naming.bind("rmi://" + server.getHostAsString() + "/Mochito",
					server);
			System.out.println("Done");
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Restarting running server");
			try {
				Naming.unbind("rmi://" + server.getHostAsString() + "/Mochito");
				Naming.rebind("rmi://" + server.getHostAsString() + "/Mochito",
						server);
				System.out.println("Done");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public MochitoServerRMI getServer() {
		return server;
	}

}
